package cn.yshujia.handler;


import cn.yshujia.utils.MinioUtils;
import cn.yshujia.utils.StringUtils;
import com.alibaba.fastjson2.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.ObjectUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author：yshujia
 * @create: 2025/4/12 14:32
 * @description: ListStringConverterHandler 处理地址 String、List 互转
 */

public abstract class ListStringConverterHandler<T> extends BaseTypeHandler<T> {
	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
		String json = null;
		if (!ObjectUtils.isEmpty(parameter)) {
			//集合转为 json
			if (parameter instanceof List) {
				json = JSON.toJSONString(parameter);
			} else {
				json = parameter.toString();
			}
			// 处理域名前缀
			if (json.contains(MinioUtils.STATIC_DOMAIN)) {
				json = json.replaceAll(MinioUtils.STATIC_DOMAIN, "");
			}
		}
		ps.setString(i, json);
	}
	
	@Override
	public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String str = rs.getString(columnName);
		return StringUtils.isEmpty(str) ? null : get(str);
	}
	
	@Override
	public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String str = rs.getString(columnIndex);
		return StringUtils.isEmpty(str) ? null : get(str);
	}
	
	@Override
	public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String str = cs.getString(columnIndex);
		return StringUtils.isEmpty(str) ? null : get(str);
	}
	
	public abstract T get(String str);
}